<template>
	<div>
		<el-form label-width="200px">
			<el-card shadow="hover">
				<template #header><span>网站设置</span></template>
				<el-form-item label="网站名称">
					<el-input v-model="formData.site_name" class="max-w-[400px]" placeholder="请输入网站名称" />
				</el-form-item>
				<el-form-item label="店铺层级数">
					<el-input v-model="formData.store_level" class="max-w-[400px]" placeholder="请输入店铺层级数" />
				</el-form-item>
				<el-form-item label="站点域名">
					<el-input v-model="formData.site_host" class="max-w-[400px]" placeholder="请输入站点域名" />
				</el-form-item>
				<el-form-item label="回源域名">
					<el-input disabled v-model="formData.cdn_origin_domain" class="max-w-[400px]" placeholder="请输入回源域名" />
				</el-form-item>
				<el-form-item label="小程序ID">
					<el-input v-model="formData.xcx_site_id" class="max-w-[400px]" placeholder="请输入小程序ID" />
				</el-form-item>
			</el-card>
			<el-card shadow="hover" class="mt-[20px]">
				<template #header><span>用户审核</span></template>
				<el-form-item label="认证检测">
					<el-radio-group v-model="formData.auth">
						<el-radio label="关闭" :value="$convert(0, formData.auth)"></el-radio>
						<el-radio label="手动审核" :value="$convert(1, formData.auth)"></el-radio>
						<el-radio label="企微自动审核" :value="$convert(2, formData.auth)"></el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="门店检测">
					<el-radio-group v-model="formData.check_user">
						<el-radio label="关闭" :value="$convert(0, formData.check_user)"></el-radio>
						<el-radio label="开启" :value="$convert(1, formData.check_user)"></el-radio>
					</el-radio-group>
				</el-form-item>
			</el-card>
			<el-card shadow="hover" class="mt-[20px]">
				<template #header><span>发课方式</span><div class="drag-tip">提示：点击并拖拽可调整顺序</div></template>
				<div class="drag-box">
					<div 
						v-for="(item, index) in formData.fakefangshi" 
						:key="item.id"
						class="drag-item"
						:draggable="true"
						@dragstart="handleDragStart($event, index)"
						@dragover="handleDragOver($event)"
						@dragenter="handleDragEnter($event, index)"
						@dragleave="handleDragLeave($event)"
						@drop="handleDrop($event, index)"
						@dragend="handleDragEnd"
					>
						<span class="drag-handle" title="拖拽排序">
							<i class="el-icon-rank"></i>
						</span>
						<el-checkbox :label="item.name" v-model="item.status" :true-value="1" :false-value="0"></el-checkbox>
						<span class="sort-number">({{ item.sort }})</span>
					</div>
				</div>
			</el-card>
			<el-card shadow="hover" class="mt-[20px]">
				<template #header><span>设置</span></template>
				<el-form-item label="销售模式">
					<div class="radio-container">
						<el-radio-group v-model="formData.sale_model">
							<el-radio label="经销商模式" :value="$convert(1, formData.sale_model)"></el-radio>
							<el-radio label="自营模式" :value="$convert(2, formData.sale_model)"></el-radio>
						</el-radio-group>
					</div>
					
					<div class="tips-container">
						经销商模式门店余额无法透支，<span class="text">自营模式门店余额可以透支</span>
					</div>
				</el-form-item>
				<!-- <el-form-item label="门店标题">
					<el-input v-model="formData.store_setting.title" class="max-w-[400px]" placeholder="请输入门店管理端标题" />
				</el-form-item>
				<el-form-item label="管理端banner">
					<upload-image v-model="formData.store_setting.banner" :limit="1"></upload-image>
				</el-form-item> -->

			</el-card>
			<!-- <el-card shadow="hover" class="mt-[20px]">
				<template #header><span>短信设置</span></template>
				<el-form-item label="短信Key">
					<el-input v-model="formData.sms_setting.sms_key" class="max-w-[400px]" placeholder="请输入短信Key" />
				</el-form-item>
				<el-form-item label="短信Secret">
					<el-input v-model="formData.sms_setting.sms_secret" class="max-w-[400px]"
						placeholder="请输入短信Secret" />
				</el-form-item>
				<el-form-item label="短信签名">
					<el-input v-model="formData.sms_setting.sms_name" class="max-w-[400px]" placeholder="请输入短信签名" />
				</el-form-item>
				<el-form-item label="短信模板ID">
					<el-input v-model="formData.sms_setting.sms_template" class="max-w-[400px]"
						placeholder="请输入短信模板ID" />
				</el-form-item>
				<el-form-item label="绑定手机号">
					<el-radio-group v-model="formData.sms_setting.bind_phone">
						<el-radio label="强制绑定" :value="$convert(1, formData.sms_setting.bind_phone)"></el-radio>
						<el-radio label="不绑定" :value="$convert(0, formData.sms_setting.bind_phone)"></el-radio>
					</el-radio-group>
				</el-form-item>
			</el-card>

			<el-card shadow="hover" class="mt-[20px]">
				<template #header><span>腾讯云设置</span></template>
				<el-form-item label="secret_id">
					<el-input v-model="formData.tencent_secret_id" />
				</el-form-item>
				<el-form-item label="secret_key">
					<el-input v-model="formData.tencent_secret_key" />
				</el-form-item>
			</el-card> -->
		</el-form>
		<div class="footer">
			<el-button type="primary" :loading="saveLoading" @click="submit">保存</el-button>
		</div>
	</div>
</template>
<script lang="ts" setup>
	import { onMounted, ref, getCurrentInstance } from "vue";
	import { getSettingInfoApi, saveSettingInfoApi } from "../../api/system";
	import { cloneDeep } from "lodash-es";
	import { ElMessage } from "element-plus";
	import { t } from "@/lang";

	const instance = getCurrentInstance() as any
	const { $convert } = instance.appContext.config.globalProperties

	const defaultFormData : ISiteSettings = {
		sale_model: 1,
		site_name: "",
		cdn_origin_domain: "",
		store_level: 0,
		site_host: "",
		check_user: 0,
		auth: 0,
		store_setting: {
			banner: "",
			title: "",
		},
		sms_setting: {
			bind_mobile: 0,
			sms_key: "",
			sms_secret: "",
			sms_name: "",
			sms_template: "",
			bind_phone: "",
		},
		fakefangshi: [
			{id: "5", name: "平台小程序", sort: 1, status: 1},
			{id: "2", name: "小程序", sort: 2, status: 1},
			{id: "4", name: "公众号", sort: 3, status: 1},
		]
	};
	const formData = ref<ISiteSettings>({ ...cloneDeep(defaultFormData) });
	const saveLoading = ref(false);
	
	// 拖拽相关状态
	let draggedIndex = -1;
	let draggedItemElement: HTMLElement | null = null;
	
	// 处理拖拽开始
	function handleDragStart(event: DragEvent, index: number) {
		console.log('拖拽开始，索引：', index);
		draggedIndex = index;
		
		// 确保获取到正确的拖拽元素
		const target = event.target as HTMLElement;
		draggedItemElement = target.closest('.drag-item') as HTMLElement;
		
		if (draggedItemElement) {
			draggedItemElement.style.opacity = '0.5';
			draggedItemElement.style.border = '2px dashed var(--el-border-color)';
		}
		
		if (event.dataTransfer) {
			event.dataTransfer.effectAllowed = 'move';
			// 设置一些数据，确保拖拽能正常工作
			event.dataTransfer.setData('text/plain', index.toString());
		}
	}
	
	// 处理拖拽经过
	function handleDragOver(event: DragEvent) {
		event.preventDefault();
		if (event.dataTransfer) {
			event.dataTransfer.dropEffect = 'move';
		}
	}
	
	// 处理拖拽进入
	function handleDragEnter(event: DragEvent, index: number) {
		event.preventDefault();
		const target = event.currentTarget as HTMLElement;
		if (target && draggedIndex !== index) {
			target.style.backgroundColor = 'var(--el-bg-color-overlay)';
			target.style.border = '1px solid var(--el-primary-color)';
		}
	}
	
	// 处理拖拽离开
	function handleDragLeave(event: DragEvent) {
		const target = event.currentTarget as HTMLElement;
		if (target) {
			target.style.backgroundColor = '';
			target.style.border = '1px solid transparent';
		}
	}
	
	// 处理放置
	function handleDrop(event: DragEvent, dropIndex: number) {
		event.preventDefault();
		event.stopPropagation();
		
		console.log('拖拽放置，原索引：', draggedIndex, '目标索引：', dropIndex);
		
		// 重置所有项的样式
		const items = document.querySelectorAll('.drag-item');
		items.forEach(item => {
			const el = item as HTMLElement;
			el.style.opacity = '';
			el.style.backgroundColor = '';
			el.style.border = '1px solid transparent';
		});
		
		// 重置被拖拽元素样式
		if (draggedItemElement) {
			draggedItemElement.style.opacity = '';
			draggedItemElement.style.border = '1px solid transparent';
		}
		
		// 验证拖拽索引是否有效
		if (draggedIndex === -1 || draggedIndex === dropIndex) {
			draggedIndex = -1;
			return;
		}
		
		// 使用Vue的响应式更新方式，确保视图正确更新
		const updatedArray = [...formData.value.fakefangshi];
		const [removed] = updatedArray.splice(draggedIndex, 1);
		updatedArray.splice(dropIndex, 0, removed);
		
		// 更新排序号
		updatedArray.forEach((item, idx) => {
			item.sort = idx + 1;
		});
		
		console.log('更新后的数组：', updatedArray);
		
		// 完全替换数组，确保响应式系统正确检测到变化
		formData.value = {
			...formData.value,
			fakefangshi: updatedArray
		};
		
		// 重置拖拽索引
		draggedIndex = -1;
		
		// 触发一个简单的视觉反馈
		// ElMessage.info('排序已更新');
	}
	
	// 处理拖拽结束（无论是否放置成功）
	function handleDragEnd() {
		console.log('拖拽结束');
		// 重置所有项的样式
		const items = document.querySelectorAll('.drag-item');
		items.forEach(item => {
			const el = item as HTMLElement;
			el.style.opacity = '';
			el.style.backgroundColor = '';
			el.style.border = '1px solid transparent';
		});
		
		// 重置被拖拽元素样式
		if (draggedItemElement) {
			draggedItemElement.style.opacity = '';
			draggedItemElement.style.border = '1px solid transparent';
		}
		
		// 重置状态
		draggedIndex = -1;
		draggedItemElement = null;
	}

	async function getSettingInfo() {
		const res = await getSettingInfoApi("system");
		formData.value = res.data as ISiteSettings;
		formData.value.sale_model = res.data?.sale_model || 1;
	}

	async function submit() {
		saveLoading.value = true;
		// 检查是否至少有一个status为1的项
		const hasActiveItem = formData.value?.fakefangshi?.some(item => item.status === 1);
		if (!hasActiveItem) {
			ElMessage.error("请至少选择一个发课方式");
			saveLoading.value = false;
			return;
		}
		try {
			// 确保sort值是正确的
			formData.value?.fakefangshi.forEach((item, index) => {
				item.sort = index + 1;
			});
			
			await saveSettingInfoApi("system", {
				content: formData.value,
			});
			ElMessage.success(t("save.success"));
		} finally {
			saveLoading.value = false;
		}
	}

	onMounted(() => {
		getSettingInfo();
	});
</script>

<style lang="scss" scoped>

	.radio-container {
		width: 100%;
	}

	.tips-container {
		color: #909399;
		font-size: 12px;
		line-height: 1.4;
		padding: 4px 0;

		.text {
			color: #ff4040;
		}
	}
	.footer {
		position: sticky;
		bottom: 0;
		margin-top: 20px;
		display: flex;
		padding: 15px;
		justify-content: center;
		background-color: var(--el-bg-color);
	}
	
	// 拖拽相关样式
	.drag-box {
		display: flex;
	}
	
	.drag-item {
		display: flex;
		align-items: center;
		padding: 8px 12px;
		border: 1px solid transparent;
		border-radius: 4px;
		transition: all 0.2s ease;
		cursor: move;
	}
	
	.drag-item:hover {
		background-color: var(--el-bg-color-overlay);
		border-color: var(--el-border-color);
	}
	
	.drag-handle {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 24px;
		height: 24px;
		margin-right: 8px;
		cursor: grab;
		color: var(--el-text-color-secondary);
	}
	
	.drag-handle:active {
		cursor: grabbing;
	}
	
	.sort-number {
		margin-left: 8px;
		color: var(--el-text-color-secondary);
		font-size: 12px;
	}
	
	.drag-tip {
		margin-top: 8px;
		font-size: 12px;
		color: var(--el-text-color-secondary);
	}
</style>